import React, { useEffect, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  Platform,
  StatusBar,
  FlatList,
  Alert,
} from "react-native";
import NoData from "../../components/preAdmin/NoData";
import query from "../../api/query";
import AsyncStorage from "@react-native-async-storage/async-storage";
import ResearchCard from "../../components/preAdmin/ResearchCard";
import LoadingBar from "../../components/InterView/LoadingBar";

const ResearchExamine = ({ navigation, route }) => {
  const [reportList, setReportList] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const { user } = route.params;
  useEffect(() => {
    const fetchData = async () => {
      try {
        setIsLoading(true);
        const token = await AsyncStorage.getItem("token");
        const result = await query.get("/report/" + user._id, {
          headers: { Authorization: token },
        });
        setReportList(result.data.data);
      } catch (err) {
        console.log("初始化调查报告出错", err);
      }
      setIsLoading(false);
    };

    let isMounted = true;
    if (isMounted) {
      fetchData();
    }
    return () => {
      isMounted = false;
    };
  }, []);

  const editResearch = async (item) => {
    try {
      setIsLoading(true);
      const token = await AsyncStorage.getItem("token");
      const result = await query.patch("/report/" + item._id, item, {
        headers: { Authorization: token },
      });

      const nowReport = reportList.map((item) => {
        return item._id === result.data.data._id ? result.data.data : item;
      });
      setReportList(nowReport);
      Alert.alert("", "调查报告审批成功", [
        {
          text: "确定",
        },
      ]);
    } catch (err) {
      console.log("调查报告审批失败", err);
      Alert.alert("", "调查报告审批成功");
    }
    setIsLoading(false);
  };

  const onPass = async (item) => {
    Alert.alert("提示", "你确定要通过该调研报告吗?", [
      {
        text: "取消",
      },
      {
        text: "确定",
        onPress: async () => {
          item.type = "pass";
          await editResearch(item);
        },
      },
    ]);
  };

  const onReject = async (item) => {
    Alert.alert("提示", "你确定要驳回该调研报告吗?", [
      {
        text: "取消",
      },
      {
        text: "确定",
        onPress: async () => {
          item.type = "reject";
          await editResearch(item);
        },
      },
    ]);
  };
  return (
    <View style={styles.container}>
      <LoadingBar visible={isLoading} />
      <FlatList
        style={{ paddingHorizontal: 10 }}
        ListHeaderComponent={
          <View
            style={{
              flexDirection: "row",
              justifyContent: "space-around",
              padding: 10,
            }}
          >
            <Text style={{ fontSize: 16 }}>调研员: {user.name}</Text>
            <Text style={{ fontSize: 16 }}>组别: {user.group}</Text>
          </View>
        }
        ListEmptyComponent={<NoData />}
        keyExtractor={(item, index) => index.toString()}
        data={reportList}
        renderItem={({ item, index }) => {
          return (
            <ResearchCard
              item={item}
              isExamine={true}
              onPass={() => onPass(item)}
              onReject={() => onReject(item)}
            />
          );
        }}
      />
    </View>
  );
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#f5f5f5",
  },
  itemSeparator: {
    width: "90%",
    height: 1,
    backgroundColor: "#ccc",
    alignSelf: "center",
  },
});

export default ResearchExamine;
